<script setup lang="ts">
import FormItem from "./FormItem.vue";
import { ref } from "vue";
import type { FormOption } from "../index";

interface Props {
  formOptions: FormOption[];
}
const props = defineProps<Props>();
const emits = defineEmits(["onSearch"]);
const formData = ref<any>({});

const onSearch = () => {
  onValidate(() => {
    emits("onSearch", formData.value);
  });
};

// 添加初始值
const addInitValue = () => {
  const obj: any = {};
  props.formOptions.forEach((v) => {
    if (v.initValue !== undefined) {
      obj[v.prop] = v.initValue;
    }
  });
  formData.value = Object.assign({}, formData.value, obj);
};

addInitValue();
const formRef = ref();
const onValidate = (callback: Function) => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      callback();
    }
  });
};

const editForm = (obj: Record<string | number | symbol, unknown>) => {
  formData.value = Object.assign({}, formData.value, obj);

  emits("onSearch", formData.value);
};
defineExpose({
  editForm,
});
</script>

<template>
  <el-form @submit.prevent ref="formRef" :model="formData" :inline="true">
    <el-form-item
      v-for="(item, index) in formOptions"
      :key="index"
      :prop="item.prop"
      :label="item.label ? item.label + ':' : ''"
      :rules="item.rules"
    >
      <form-item v-model="formData[item.prop]" :item="item" @onSearch="onSearch" />
    </el-form-item>
    <slot name="formMore" />
    <el-form-item class="searchForm-btns">
      <el-button type="primary" @click="onSearch">查询 </el-button>

      <slot name="btns" />
    </el-form-item>
  </el-form>
</template>

<style lang="scss">
.searchForm-btns {
  button + .#{$namespace}-dropdown {
    margin-left: 15px;
  }
  .#{$namespace}-button {
    padding: 8px 20px;
  }
  ::v-deep .#{$namespace}-input__inner {
    flex: 1;
    width: 0;
  }
}
</style>
